package rexsee.service;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Handler;

public class RexseePushSmsListener implements JavascriptInterface {

	public static final String INTERFACE_NAME = "PushSmsListener";
	@Override
	public String getInterfaceName() {
		return (smsBrowser == null) ? null : smsBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseePushSmsListener(childBrowser);
	}

	public static final String CONTENT_URI_SMS = "content://sms";
	public static final String CONTENT_URI_SMS_INBOX = "content://sms/inbox";
	public static final String CONTENT_URI_SMS_CONVERSATIONS = "content://sms/conversations";

	private final Context smsContext;
	private final Browser smsBrowser;
	public RexseePushSmsListener(Context context) {
		smsContext = context;
		smsBrowser = null;
		RexseePush.initDatabase(context);
	}
	public RexseePushSmsListener(Browser browser) {
		smsContext = browser.getContext();
		smsBrowser = browser;
		RexseePush.initDatabase(smsContext);
	}

	public void register() {
		smsContext.getContentResolver().registerContentObserver(Uri.parse(CONTENT_URI_SMS), true, new ContentObserver(new Handler()) {
			@Override
			public void onChange(boolean selfChange) {
				super.onChange(selfChange);
				if (deliverSelfNotifications()) return;
				try {
					String[] smsNumbers = (new RexseePushSmsListener(smsContext)).getItems();
					ContentResolver contentResolver = smsContext.getContentResolver();
					Cursor cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS_INBOX), new String[]{"_id", "thread_id", "address", "person", "date", "body", "read"}, " read=?", new String[]{"0"}, "date desc");
					for (int i = 0; i < cursor.getCount(); i++) {
						cursor.moveToPosition(i);
						if (inSms(cursor.getString(2), smsNumbers)) {
							contentResolver.delete(Uri.parse(CONTENT_URI_SMS_CONVERSATIONS + "/" + cursor.getLong(1)), " _id=?", new String[]{"" + cursor.getInt(0)});
							RexseePush.add(smsContext, RexseePush.PUSH_TYPE_SMS, cursor.getLong(4), cursor.getString(2), cursor.getString(5));
						}
					}
					cursor.close();
				} catch (Exception e) {
				}
			}
		});
	}
	private boolean inSms(String str, String[] array) {
		if (array == null) return false;
		for (int i = 0; i < array.length; i++)
			if (str.endsWith(array[i])) return true;
		return false;
	}
	private String[] getItems() {
		SQLiteDatabase db = smsContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
		Cursor cursor = db.rawQuery("SELECT * from " + RexseePush.TABLE_PUSH_SMS + ";", null);
		if (cursor == null) {
			db.close();
			return null;
		}
		int count = cursor.getCount();
		if (count == 0) {
			cursor.close();
			db.close();
			return null;
		}
		String[] rtn = new String[count];
		for (int i = 0; i < count; i++) {
			cursor.moveToPosition(i);
			rtn[i] = cursor.getString(0);
		}
		try {
			cursor.close();
		} catch (Exception e) {
		}
		db.close();
		return rtn;
	}

	//JavaScript Interface
	public boolean contains(String phoneNumber) {
		return inSms(phoneNumber, getItems());
	}
	public void add(String phoneNumber) {
		try {
			SQLiteDatabase db = smsContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
			db.execSQL("DELETE FROM " + RexseePush.TABLE_PUSH_SMS + " WHERE phoneNumber='" + phoneNumber + "';");
			db.execSQL("INSERT INTO " + RexseePush.TABLE_PUSH_SMS + " VALUES ('" + phoneNumber + "');");
			db.close();
		} catch (Exception e) {
		}
	}
	public String get() {
		String[] tmp = getItems();
		if (tmp == null) return "";
		String rtn = "";
		for (int i = 0; i < tmp.length; i++) {
			rtn += (i == 0) ? "\"" + tmp[i] + "\"" : ",\"" + tmp[i] + "\"";
		}
		return "[" + rtn + "]";
	}
	public void remove(String phoneNumber) {
		try {
			SQLiteDatabase db = smsContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
			db.execSQL("DELETE FROM " + RexseePush.TABLE_PUSH_SMS + " WHERE phoneNumber='" + phoneNumber + "';");
			db.close();
		} catch (Exception e) {
		}
	}

}
